package com.example.udpcommunication;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    Button sendBtn, decideBtn;
    EditText sendMsg, ipEd;
    TextView receiveMsg;
    // 对方的ip地址
    String ip;
    UdpTool udpTool;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        // 发送信息的函数
        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //在Android通信协议必须要放在线程里面进行
                String str = sendMsg.getText().toString();
                Log.v("发送", str);
                if (ip!=null){
                    udpTool.sendMessage(str,ip);
                }else {
                    Toast.makeText(MainActivity.this, "请输入对方ip和端口", Toast.LENGTH_SHORT).show();
                }
            }

        });
        decideBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ip = ipEd.getText().toString();
                Toast.makeText(MainActivity.this, "确定成功！", Toast.LENGTH_SHORT).show();
            }
        });
        // 接收信息的函数
        try {
            udpTool.receiveMessage(receiveMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void initView() {
        sendBtn = findViewById(R.id.send_btn);
        sendMsg = findViewById(R.id.send_message);
        receiveMsg = findViewById(R.id.receive_message);
        ipEd = findViewById(R.id.target_ip_ed);
        decideBtn = findViewById(R.id.decide_btn);
        udpTool = new UdpTool(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放资源
        udpTool.closeSocket();
    }
}